//
//  LoginViewController.m
//  FMS
//
//  Created by Steven on 10/10/13.
//  Copyright (c) 2013 QGSVN. All rights reserved.
//

#import "LoginViewController.h"
#import "ForgotPasswordViewController.h"
#import "FMSServerAPI.h"
#import "ListServerVCNew.h"
#import "NSString+Extension.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize myProgressView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loginSuccess) name:kLoginSuccessSynNow object:nil];
    BOOL checkRemember = [[[NSUserDefaults standardUserDefaults] objectForKey:USER_REMEMBER] boolValue];
    _btnCheckBox.selected = checkRemember;
    if (checkRemember) {
        _txtUsername.text = [[NSUserDefaults standardUserDefaults] objectForKey:USER_EMAIL];
        _txtPassword.text = [[NSUserDefaults standardUserDefaults] objectForKey:USER_PASS];
    }
    else{
        _txtUsername.text = @"";
        _txtPassword.text = @"";
    }
    
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kLoginSuccessSynNow object:nil];
}
- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    
    myProgressView = [[CMTwoToneProgressBar alloc] initWithFrame:CGRectMake(370, 543, 280, 20)];
    [self.view addSubview:myProgressView];
    [self.myProgressView setProgressBarColor:APPLE_BLUE_COLOR];
    [self.myProgressView setProgress:0 animated:YES];
    self.myProgressView.hidden = YES;
    
    // Do any additional setup after loading the view from its nib.
    AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    dictLanguage = [delegate.arrayLanguage objectAtIndex:0];
    
    //set title by language key for labels and button
    _txtUsername.placeholder = [dictLanguage objectForKey:@"login.username"];
    _txtPassword.placeholder = [dictLanguage objectForKey:@"login.password"];
    _lbRememberMe.text  = [dictLanguage objectForKey:@"login.remember"];
    [_btnForgotPassword setTitle:[dictLanguage objectForKey:@"login.forgot-password"] forState:UIControlStateNormal];
    [_btnSignIn setTitle:[dictLanguage objectForKey:@"login.sign-in"] forState:UIControlStateNormal];
    
    //set border for text field
    _txtUsername.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _txtUsername.layer.borderWidth = 1;
    
    _txtPassword.layer.borderColor = [UIColor lightGrayColor].CGColor;
    _txtPassword.layer.borderWidth = 1;
    
    //add 2 icon: user and lock to textfield
    UIImageView *imgUserView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_user.png"]];
    
    UIImageView *imgLockView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_lock.png"]];
    
    [_txtUsername setLeftViewMode:UITextFieldViewModeAlways];
    _txtUsername.leftView = imgUserView;
    
    [_txtPassword setLeftViewMode:UITextFieldViewModeAlways];
    _txtPassword.leftView = imgLockView;
    
    //set background for Sign in button
    _btnSignIn.layer.cornerRadius = 5;
    _btnSignIn.contentMode=UIViewContentModeScaleAspectFill;
    _btnSignIn.clipsToBounds=YES;
    
    [_btnSignIn setBackgroundImage:[AppDelegate imageFromColor:APPLE_BLUE_COLOR] forState:UIControlStateNormal];
    [_btnSignIn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
//    [_btnSignIn setBackgroundImage:[AppDelegate imageFromColor:[UIColor whiteColor]] forState:UIControlStateHighlighted];
    [_btnSignIn setTitleColor:APPLE_BLUE_COLOR forState:UIControlStateHighlighted];
    
    //listen keyboard appear
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidShow) name:UIKeyboardDidShowNotification object:nil];
    
    //listen keyboard disappear
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardDidHide) name:UIKeyboardDidHideNotification object:nil];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)tapCheckBox:(id)sender {
    [_btnCheckBox setSelected:!_btnCheckBox.isSelected];
}

- (IBAction)tapForgotPassword:(id)sender {
    ForgotPasswordViewController *controller = [[ForgotPasswordViewController alloc] initWithNibName:@"ForgotPasswordViewController" bundle:[NSBundle mainBundle]];
    [self.navigationController pushViewController:controller animated:YES];
}
- (void)loginSuccess{

    [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:_btnCheckBox.selected] forKey:USER_REMEMBER];
    [[NSUserDefaults standardUserDefaults] setObject:_txtUsername.text forKey:USER_EMAIL];
    [[NSUserDefaults standardUserDefaults] setObject:_txtPassword.text forKey:USER_PASS];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
//    //save password current
//    NSMutableDictionary *userInfo = [[CouchBaseLiteLib sharedCouchBaseLite] getUserByEmail:_txtUsername.text];
//    if ([userInfo objectForKey:@"email"] && [[userInfo objectForKey:@"email"] isEqualToString:_txtUsername.text]) {
//        NSString *passAuth = [AppDelegate encryptInfo:_txtPassword.text error:nil];
//        [[CouchBaseLiteLib sharedCouchBaseLite] updateUserAccount:passAuth newDict:userInfo];
//        
//    }
    
    //create all design views to query data
    NSNumber *isInitDesignView = [[NSUserDefaults standardUserDefaults] objectForKey:@"isInitDesignView"];
    if (![isInitDesignView boolValue])
        [[CouchBaseLiteLib sharedCouchBaseLite] initAllViews];
    
    [self performSelector:@selector(delayAfterLogin) withObject:self afterDelay:1];
}

- (void) delayAfterLogin {
    [self stopSigningInView];
    AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [delegate loginSuccess];
}

- (void)savePermissionInfo:(NSMutableDictionary *)infoDict{
    NSMutableDictionary *permissionDict;
#ifndef vDEBUG
    permissionDict = infoDict;
#else
    permissionDict = [infoDict objectForKey:@"permission"];
#endif
    
    
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"buildingManagement"] forKey:BUILDING_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"facilityManagement"] forKey:FACILITY_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"maintenanceManagement"] forKey:MAINTENANCE_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"liaisonManagement"] forKey:LIAISON_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"scheduling"] forKey:SCHEDULE_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"reporting"] forKey:REPORTING_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"checklist"] forKey:CHECKLIST_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"technicalAssessment"] forKey:TECHNICAL_ASSESSMENT_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"approval"] forKey:APPROVAL_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"report"] forKey:M_REPORT_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"workRequest"] forKey:WORK_REQUEST_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"costing"] forKey:COSTING_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"epo"] forKey:EPO_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"rap"] forKey:RAP_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"coc"] forKey:COC_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"gr"] forKey:GR_PERMISSION];
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"invoice"] forKey:INVOICE_PERMISSION];
    @try {
        [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"eot"] forKey:ETO_PERMISSION];
    }
    @catch (NSException *e) {
        NSLog(@"%@",e);
        NSMutableDictionary *etoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
        [[NSUserDefaults standardUserDefaults] setObject:etoDict forKey:ETO_PERMISSION];
    }
    NSLog(@"permission = %@",[permissionDict objectForKey:@"workcomplete"]);
    [[NSUserDefaults standardUserDefaults] setObject:[permissionDict objectForKey:@"workcomplete"] forKey:WORK_COMPLETE_PERMISSION];
    [[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)checkPermsionUserLogin:(BOOL)checkLocal{
    if (checkLocal) {
        NSMutableDictionary *userInfo = [[CouchBaseLiteLib sharedCouchBaseLite] getUserByEmail:_txtUsername.text];
        NSString *passwordAuth = [userInfo objectForKey:@"passwordEncrypted"];
        NSString *password = [AppDelegate decryptInfo:passwordAuth error:nil];
        if (passwordAuth && [password isEqualToString:_txtPassword.text]){
            
            NSString *roleName = [userInfo objectForKey:@"role"];
            NSMutableDictionary *permission = [[CouchBaseLiteLib sharedCouchBaseLite] getPermissionByRoleName:roleName];
            if (permission && [permission objectForKey:@"permission"]) {
                [[NSUserDefaults standardUserDefaults] setObject:[userInfo objectForKey:@"_id"] forKey:ACCOUNT_ID];
                [[NSUserDefaults standardUserDefaults] setObject:[userInfo objectForKey:@"name"] forKey:ACCOUNT_NAME];
                [[NSUserDefaults standardUserDefaults] setObject:[userInfo objectForKey:@"phone"] forKey:ACCOUNT_PHONE];
                [[NSUserDefaults standardUserDefaults] setObject:[userInfo objectForKey:@"address"] forKey:ACCOUNT_ADDRESS];
                [[NSUserDefaults standardUserDefaults] setObject:[userInfo objectForKey:@"company"] forKey:ACCOUNT_COMPANY];
                [[NSUserDefaults standardUserDefaults] setObject:[userInfo objectForKey:@"role"] forKey:ACCOUNT_ROLE];
                [[NSUserDefaults standardUserDefaults] setObject:permission forKey:ACCOUNT_PERMISSION];
                [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"isLogin"];
                
                [[NSUserDefaults standardUserDefaults] synchronize];
                [self loginSuccess];
                
                [self savePermissionInfo:[permission objectForKey:@"permission"]];
            
            }
            else{
                [self loginOnline];
            }
        }
        else{
//            [self loginOnline];
            [self stopSigningInView];
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.failed.login-acccount"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
            [dialog show];
        }
    }
    else{
        [self loginOnline];
    }
}

- (void) proccessAuthentication {
    
    //webservice
    int numberUser = [[CouchBaseLiteLib sharedCouchBaseLite] countUser];
//    if (numberUser <= 0) {
//        [self checkPermsionUserLogin:NO];
//    }
//    else{
//        [self checkPermsionUserLogin:YES];
//    }
    //always check login online first, after logging in success check this password and encrypt it.
    [self checkPermsionUserLogin:NO];
}

- (void)processAfterLogin:(NSMutableDictionary *)info{

    [[NSUserDefaults standardUserDefaults] setObject:[info objectForKey:@"id"] forKey:ACCOUNT_ID];
    [[NSUserDefaults standardUserDefaults] setObject:[info objectForKey:@"name"] forKey:ACCOUNT_NAME];
    [[NSUserDefaults standardUserDefaults] setObject:[info objectForKey:@"phone"] forKey:ACCOUNT_PHONE];
    [[NSUserDefaults standardUserDefaults] setObject:[info objectForKey:@"address"] forKey:ACCOUNT_ADDRESS];
    [[NSUserDefaults standardUserDefaults] setObject:[info objectForKey:@"company"] forKey:ACCOUNT_COMPANY];
    [[NSUserDefaults standardUserDefaults] setObject:[info objectForKey:@"role"] forKey:ACCOUNT_ROLE];
    [[NSUserDefaults standardUserDefaults] setObject:[info objectForKey:@"permission"] forKey:ACCOUNT_PERMISSION];

    [[NSUserDefaults standardUserDefaults] synchronize];
 #ifndef vDEBUG
    if ([info objectForKey:@"linkRemoteDb"]) {
        //clear local database to sync now
//        [[CouchBaseLiteLib sharedCouchBaseLite] deleteLocalDatabaseWithParent:nil];

        BOOL ssl = FALSE;
        NSMutableDictionary *linkRemoteDB = [info objectForKey:@"linkRemoteDb"];
        NSString *server = [linkRemoteDB objectForKey:@"server"];
        NSString *port = [linkRemoteDB objectForKey:@"port"];
        NSString *databaseName = [linkRemoteDB objectForKey:@"nameDb"];
        NSString *remoteServerLink;
        if (ssl)
            remoteServerLink = @"https";
        else
            remoteServerLink = @"http";
        if ([port intValue] <= 0)
            ;
        else
            remoteServerLink = [remoteServerLink stringByAppendingFormat:@"://%@:%d",server,[port intValue]];
        remoteServerLink = [remoteServerLink stringByAppendingFormat:@"/%@",databaseName];
        
        NSString *authName = [linkRemoteDB objectForKey:@"admin"];
        NSString *authHastable = [linkRemoteDB objectForKey:@"password"];
        
        [self savePermissionInfo:[info objectForKey:@"permission"]];
        
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys:authName,@"username",authHastable,@"password", nil];
    
        [[FMSLib shareClient] getTimeDurationSuccess:^(NSMutableDictionary *success){
            [[NSUserDefaults standardUserDefaults] setObject:[success objectForKey:@"time"] forKey:TIME_DURATION_DB_SERVER];
            
            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"isLogin"];
            
            [[NSUserDefaults standardUserDefaults] synchronize];

            [[CouchBaseLiteLib sharedCouchBaseLite] setContinuous:YES];
            
            [[CouchBaseLiteLib sharedCouchBaseLite] setRemoteDatebaseUrl:remoteServerLink authenticateUser:dict];
            [[NSUserDefaults standardUserDefaults] synchronize];
//            [[CouchBaseLiteLib sharedCouchBaseLite] syncNow];
            
            //display progress bar
//            self.myProgressView.hidden = NO;
            
        }failure:^(NSError *error){
            [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:TIME_DURATION_DB_SERVER];
            [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"isLogin"];
            
            [[CouchBaseLiteLib sharedCouchBaseLite] setContinuous:YES];
            [[CouchBaseLiteLib sharedCouchBaseLite] setRemoteDatebaseUrl:remoteServerLink authenticateUser:dict];
            [[NSUserDefaults standardUserDefaults] synchronize];
//            [[CouchBaseLiteLib sharedCouchBaseLite] syncNow];
        }];
    }
#else
    [[NSNotificationCenter defaultCenter] postNotificationName:kLoginSuccessSynNow object:nil];
    
    /************** CREATE TEST PERMISSION DATA ************/
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    [userDefault setObject:@"ma" forKey:ACCOUNT_ROLE];
    //test create permission for Building Mgmt
    NSMutableDictionary *detailInfoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update", nil];
    NSMutableDictionary *aipDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update", [NSNumber numberWithBool:YES],@"add",nil];
    NSMutableDictionary *maintenanceDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    NSMutableDictionary *notificationDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"schedule", nil];
    
    NSMutableDictionary *buildingMgmtDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:detailInfoDict,@"detailsInfo",aipDict,@"aip",maintenanceDict,@"maintenanceManagement",documentDict,@"documentAttachment",notificationDict,@"notification", nil];
    [userDefault setObject:buildingMgmtDict forKey:BUILDING_PERMISSION];
    
    //Facility Mgmt
    detailInfoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update", nil];
    NSMutableDictionary *ampDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update", [NSNumber numberWithBool:YES],@"add",nil];
    maintenanceDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    documentDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    notificationDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"schedule", nil];
    
    NSMutableDictionary *facilityMgmtDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:detailInfoDict,@"detailsInfo",ampDict,@"aip",maintenanceDict,@"maintenanceManagement",documentDict,@"documentAttachment",notificationDict,@"notification", nil];
    [userDefault setObject:facilityMgmtDict forKey:FACILITY_PERMISSION];
    
    //Maintenance Mgmt
    NSMutableDictionary *inspectionDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    maintenanceDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    
    NSMutableDictionary *maintenanceMgmtDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:inspectionDict,@"inspection",maintenanceDict,@"maintenance", nil];
    [userDefault setObject:maintenanceMgmtDict forKey:MAINTENANCE_PERMISSION];
    
    //Scheduling
    NSMutableDictionary *schedulingMgmtDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:schedulingMgmtDict forKey:SCHEDULE_PERMISSION];
    
    //Reporting
    NSMutableDictionary *reportingMgmtDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:reportingMgmtDict forKey:REPORTING_PERMISSION];
    
    //Liaison
    NSMutableDictionary *liaisonMgmtDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:liaisonMgmtDict forKey:LIAISON_PERMISSION];
    
    //checklist
    NSMutableDictionary *checklistDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:checklistDict forKey:CHECKLIST_PERMISSION];
    
    //technical assessment
    NSMutableDictionary *taDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:taDict forKey:TECHNICAL_ASSESSMENT_PERMISSION];
    
    //report
    NSMutableDictionary *reportDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:reportDict forKey:REPORTING_PERMISSION];
    
    //workrequest
    NSMutableDictionary *workRequestDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:workRequestDict forKey:WORK_REQUEST_PERMISSION];
    
    //costing
    NSMutableDictionary *costingDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:costingDict forKey:COSTING_PERMISSION];
    
    //approval
    NSMutableDictionary *approvalDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:approvalDict forKey:APPROVAL_PERMISSION];
    
    //epo
    NSMutableDictionary *epoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:epoDict forKey:EPO_PERMISSION];
    
    //rap
    NSMutableDictionary *rapDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:rapDict forKey:RAP_PERMISSION];
    
    //coc
    NSMutableDictionary *cocDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:cocDict forKey:COC_PERMISSION];
    
    //gr
    NSMutableDictionary *grDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:grDict forKey:GR_PERMISSION];
    
    //invoice
    NSMutableDictionary *invoiceDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:invoiceDict forKey:INVOICE_PERMISSION];
    
    //eto
    NSMutableDictionary *etoDict = [NSMutableDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithBool:YES],@"access",[NSNumber numberWithBool:YES],@"update",[NSNumber numberWithBool:YES],@"add", nil];
    [userDefault setObject:etoDict forKey:ETO_PERMISSION];
    
    /******** END TEST PERMISSION DATA **************/
#endif
    
}
- (void)stopSigningInView
{
    self.view.userInteractionEnabled = YES;
    [_btnSignIn stopActivityIndicator];
    [_btnSignIn setTitle:[dictLanguage objectForKey:@"login.sign-in"] forState:UIControlStateNormal];
}
- (void)loginOnline{
#ifndef vDEBUG
    [[FMSLib shareClient] loginWithUser:_txtUsername.text password:_txtPassword.text successs:^(NSMutableDictionary *responese){
        //create all view to speed up performance
//        [[CouchBaseLiteLib sharedCouchBaseLite] initAllViews];
        
        //encrypt password and save to db
        //save password current
        NSMutableDictionary *userInfo = [[CouchBaseLiteLib sharedCouchBaseLite] getUserByEmail:_txtUsername.text];
        if ([userInfo objectForKey:@"email"] && [[userInfo objectForKey:@"email"] isEqualToString:_txtUsername.text]) {
            NSString *passAuth = [AppDelegate encryptInfo:_txtPassword.text error:nil];
            [[CouchBaseLiteLib sharedCouchBaseLite] updateUserAccount:passAuth newDict:userInfo];
        }
        [[NSUserDefaults standardUserDefaults] setObject:[NSNumber numberWithBool:YES] forKey:@"isLogin"];
        //process login
        [self processAfterLogin:responese];
    } failure:^(NSError *error){
//        [self stopSigningInView];
//        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.failed.login-acccount"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
//        [dialog show];
        //self check login offline
        [self checkPermsionUserLogin:YES];
    }];
#else
    [self processAfterLogin:Nil];
#endif
}
- (IBAction)tapSignIn:(id)sender {
    //check validate for inputting username
    if (_txtUsername.text == nil || [_txtUsername.text isEqualToString:@""]) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.username.blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
    NSString *emailRegexString	= @"^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
    if (![_txtUsername.text isMatchedByRegex:emailRegexString]) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.username.blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
    //check validate for inputting password
    if (_txtPassword.text == nil || [_txtPassword.text isEqualToString:@""]) {
        UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:[dictLanguage objectForKey:@"general.warning"] message:[dictLanguage objectForKey:@"login.password.blank"] delegate:nil cancelButtonTitle:[dictLanguage objectForKey:@"general.ok"] otherButtonTitles:nil];
        [dialog show];
        return;
    }
    
//    [self loginSuccess];
    //process login
//    AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
//    [delegate loginSuccess];
    
    self.view.userInteractionEnabled = NO;
    [_btnSignIn setTitle:[dictLanguage objectForKey:@"login.signing-in"] forState:UIControlStateNormal];
    [_btnSignIn startActivityIndicator];
    
    [self performSelector:@selector(proccessAuthentication) withObject:self afterDelay:0.5];
}

- (IBAction)changeServer:(id)sender {
    UIButton *btnSender = (UIButton *)sender;
    
    ListServerVCNew *controller = [[ListServerVCNew alloc] initWithNibName:nil bundle:nil parent:self];
    UINavigationController *naviController = [[UINavigationController alloc] initWithRootViewController:controller];
    popController = [[UIPopoverController alloc] initWithContentViewController:naviController];
    [popController presentPopoverFromRect:btnSender.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}

- (void)dismissPopoverController{
    [popController dismissPopoverAnimated:YES];
    popController = nil;
}
- (void) keyboardDidShow {
    _containerView.center = CGPointMake(_containerView.center.x, 300);
}

- (void) keyboardDidHide {
    _containerView.center = CGPointMake(_containerView.center.x, 400);
}
#pragma mark UITextFieldDelegate
-(BOOL) textFieldShouldReturn:(UITextField *)textField
{
    if (textField == _txtUsername) {
        [_txtPassword becomeFirstResponder];
    }
    else {
        //process login
        [self tapSignIn:nil];
    }
    return YES;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void) dealloc {
    NSLog(@"%@ dealloc",self);
}

@end
